<template>
  <div id="bills" class="card col-12 px-0 mt-5">
    <nav aria-label="breadcrumb" role="navigation">
      <ol class="breadcrumb pb-0">
        <li class="breadcrumb-item ms-1" aria-current="page">账单</li>
        <li class="breadcrumb-item active" aria-current="page">列表</li>

        <li class="breadcrumb-item ms-auto d-none">
          <router-link to="/bills/unreviewed">待审核</router-link>
        </li>
        <li class="breadcrumb-item d-none">
          <router-link to="/bills/toSettle">待结算</router-link>
        </li>
        <li class="breadcrumb-item d-none">
          <router-link to="/ent/settlements">结算单</router-link>
        </li>
        <li class="breadcrumb-item d-none">
          <router-link to="/ent/receipts">收款单</router-link>
        </li>
      </ol>
    </nav>
    <template v-if="showSearchForm">
      <div class="card-body px-1">
        <form>
          <div class="row mb-2">
            <select class="form-select" v-model.number="billType">
              <option value="-1">类别</option>
              <option value="0">机票</option>
              <option value="5">退票</option>
              <option value="7">改签</option>
              <option value="6">服务</option>
              <option value="2">酒店</option>
              <option value="3">火车票</option>
              <option value="4">租车</option>
            </select>
          </div>
          <div class="row mb-2">
            <select class="form-select" v-model.number="intlTicket">
              <option value="-1">类型</option>
              <option value="0">国内</option>
              <option value="1">国际</option>
            </select>
          </div>
          <div class="row mb-2">
            <select class="form-select" v-model.number="payType">
              <option value="0">收款方式</option>
              <option value="1">现金</option>
              <option value="2">信用卡</option>
              <option value="4">支票</option>
              <option value="8">记账</option>
            </select>
          </div>
          <div class="row mb-2">
            <select class="form-select" v-model.number="reviewed">
              <option value="-1">审核</option>
              <option value="0">未审核</option>
              <option value="1">已审核</option>
            </select>
          </div>
          <div class="row mb-2">
            <select class="form-select" v-model.number="bePaid">
              <option value="-1">收款</option>
              <option value="0">未收</option>
              <option value="1">已收</option>
            </select>
          </div>
          <div class="row mb-2">
            <select class="form-select" v-model.number="paymentStatus">
              <option value="-1">付款</option>
              <option value="0">未付</option>
              <option value="1">已付</option>
            </select>
          </div>
          <div class="row mb-2">
            <my-select-customer
              :customerId.sync="customerId"
              :enterpriseType="1"
            ></my-select-customer>
          </div>
          <div class="row mb-2">
            <my-select-supplier
              :supplierId.sync="supplierId"
            ></my-select-supplier>
          </div>
          <div class="row mb-2">
            <my-date-picker
              id="date0"
              v-model="beginDate"
              placeholder="账单日期从"
              sizing="sm"
            ></my-date-picker>
          </div>
          <div class="row mb-2">
            <my-date-picker
              id="date1"
              v-model="endDate"
              placeholder="账单日期到"
              sizing="sm"
            ></my-date-picker>
          </div>
          <div class="row mb-2">
            <my-date-picker
              id="date2"
              v-model="etdzDateBegin"
              placeholder="出票日期从"
              sizing="sm"
            ></my-date-picker>
          </div>
          <div class="row mb-2">
            <my-date-picker
              id="date3"
              v-model="etdzDateEnd"
              placeholder="出票日期到"
              sizing="sm"
            ></my-date-picker>
          </div>
          <div class="row mb-2">
            <my-date-picker
              id="date4"
              v-model="auditDateBegin"
              placeholder="审核日期从"
              sizing="sm"
            ></my-date-picker>
          </div>
          <div class="row mb-2">
            <my-date-picker
              id="date5"
              v-model="auditDateEnd"
              placeholder="审核日期到"
              sizing="sm"
            ></my-date-picker>
          </div>
          <div class="row mb-2">
            <my-date-picker
              id="date6"
              v-model="settleDateBegin"
              placeholder="结算日期从"
              sizing="sm"
            ></my-date-picker>
          </div>
          <div class="row mb-2">
            <my-date-picker
              id="date7"
              v-model="settleDateEnd"
              placeholder="结算日期到"
              sizing="sm"
            ></my-date-picker>
          </div>
          <div class="row mb-2">
            <input
              type="textfield"
              class="form-control"
              size="8"
              placeholder="账单号"
              v-model.trim="billNum"
            />
          </div>
          <div class="row mb-2">
            <input
              type="textfield"
              class="form-control"
              size="8"
              placeholder="订单号"
              v-model.trim="orderNo"
            />
          </div>
          <div class="row mb-2">
            <input
              type="textfield"
              class="form-control"
              size="8"
              placeholder="原始单号"
              v-model.trim="flightOrderNo"
            />
          </div>
          <div class="row mb-2">
            <input
              type="textfield"
              class="form-control"
              size="8"
              placeholder="账单备注"
              v-model.trim="remark"
            />
          </div>
          <div class="row mb-2">
            <input
              type="textfield"
              class="form-control"
              size="8"
              placeholder="成本中心"
              v-model.trim="costCenter"
            />
          </div>
          <div class="row mb-2">
            <input
              type="textfield"
              class="form-control"
              size="8"
              placeholder="结算单号"
              v-model.trim="settlementNo"
            />
          </div>
          <div class="row mb-2">
            <label>每页记录数</label>
            <select class="form-select" v-model.number="sc.pageSize">
              <option value="2">2</option>
              <option value="5">5</option>
              <option value="10">10</option>
              <option value="20">20</option>
              <option value="25">25</option>
              <option value="30">30</option>
              <option value="50">50</option>
              <option value="100">100</option>
              <option value="200">200</option>
              <option value="500">500</option>
            </select>
          </div>
          <div class="row mb-2">
            <label>排序</label>
            <select class="form-select" v-model.number="orderBy">
              <option value="0">默认</option>
              <option value="3">时间降序</option>
            </select>
          </div>
          <div class="row mb-2">
            <button
              type="button"
              class="btn btn-primary mb-2"
              @click.stop="searchBills()"
            >
              确定
            </button>
            <button
              type="button"
              class="btn btn-secondary btn-sm"
              @click.stop="reset()"
            >
              重置
            </button>

            <div class="ms-auto d-none">
              <router-link to="/setting/bill-templates">下载模板</router-link>
              <select class="form-select" v-model.number="downloadFormat">
                <option value="0">默认格式</option>
                <option value="1">格式一</option>
                <template v-for="info in templates">
                  <option :value="info.templateNo">{{ info.name }}</option>
                </template>
              </select>
              <a
                class="btn btn-success ms-auto"
                @click.stop="downloadBillInfo()"
                href="#"
                >下载</a
              >
            </div>
          </div>
        </form>
      </div>
    </template>
    <template v-else>
      <div class="card-header">
        <!-- <router-link class="btn btn-success ms-auto" to="/h5/new/flt/order">新建</router-link> -->
        <button
          type="button"
          class="btn btn-primary float-end"
          @click.stop="showSearchOption()"
        >
          查找
        </button>
      </div>
      <table class="table table-striped table-hover table-sm">
        <thead>
          <tr class="bg-info">
            <th class="d-none d-md-table-cell">类别</th>
            <th>账单号</th>
            <th>日期</th>
            <th class="d-none d-md-table-cell">订单号</th>
            <th>客户</th>
            <th class="d-none d-md-table-cell">代码/成本/项目</th>
            <th class="d-none d-md-table-cell">供应商</th>
            <th class="d-none d-md-table-cell">收款方式</th>

            <th class="d-none d-md-table-cell">审核日期</th>
            <th class="d-none d-md-table-cell">结算</th>
            <th class="d-none d-md-table-cell">收支</th>
            <th class="text-end">金额</th>
            <th class="text-end d-none d-md-table-cell">成本</th>
            <th class="text-end d-none d-md-table-cell">利润</th>
            <th class="d-none d-md-table-cell">预订员</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          <template v-for="info in orders">
            <tr :key="info.id" @click.stop="showDetail(info.id)">
              <td class="d-none d-md-table-cell">
                {{ showBillTypeDesc(info.billType) }}
                <span v-if="info.intlTicket === 0">(国内)</span>
                <span class="text-danger" v-else-if="info.intlTicket === 1"
                  >(国际)</span
                >
              </td>
              <td>{{ info.billNum }}</td>
              <td>{{ info.opDate.substring(5) }}</td>
              <td class="d-none d-md-table-cell">{{ info.orderNo }}</td>
              <td>
                {{ showCustomerName(info) }}
              </td>
              <td class="d-none d-md-table-cell">
                {{ info.customerCode }}/{{ info.costCenter }}/{{
                  info.projectName
                }}
              </td>
              <td class="d-none d-md-table-cell">
                <span v-if="info.supplier !== null">{{
                  info.supplier.name
                }}</span>
              </td>

              <td class="d-none d-md-table-cell">{{ info.payTypeNoteDesc }}</td>
              <td class="d-none d-md-table-cell">
                <template
                  v-if="info.audited === '1' && info.auditDate !== null"
                >
                  <span class="small">{{ info.auditDate }}</span>
                </template>
                <template v-else-if="info.audited === '1'">
                  <span class="small">已审核</span>
                </template>
                <template v-else>
                  <span class="text-danger small">未审核</span>
                </template>
              </td>
              <td class="d-none d-md-table-cell">
                <span class="small" v-if="info.settlementNo !== null">
                  {{ info.settleDate }} <br />
                  {{ info.settlementNo }}
                </span>
                <span class="text-danger small" v-else-if="info.bePaid === '0'"
                  >未结算</span
                >
              </td>
              <td class="d-none d-md-table-cell">
                <span class="text-danger small" v-if="info.bePaid === '1'"
                  >已收 {{ info.receiptNo }} /
                </span>
                <span class="small" v-if="info.paymentStatus === 1">已付</span>
              </td>
              <td class="text-end">{{ info.billSum }}</td>
              <td class="text-end d-none d-md-table-cell">{{ info.cost }}</td>
              <td class="text-end d-none d-md-table-cell">
                {{ info.profit }}
              </td>

              <td class="d-none d-md-table-cell">{{ info.op1 }}</td>
              <td class="d-none d-md-table-cell">
                <template v-if="info.audited !== '1' && isAdmin">
                  <button
                    type="button"
                    class="btn btn-sm btn-success"
                    @click.stop="auditBillDone(info.id)"
                  >
                    审核通过
                  </button>
                </template>
                <template v-else-if="info.audited === '1' && isAdmin">
                  <template v-if="info.bePaid !== '1'">
                    <button
                      type="button"
                      class="btn btn-sm btn-success"
                      @click.stop="writeOffBill(info.id)"
                    >
                      已收
                    </button>
                  </template>

                  <template v-if="info.paymentStatus === 0">
                    <button
                      type="button"
                      class="btn btn-sm btn-warning ms-2"
                      @click.stop="finishPayment(info.id)"
                    >
                      已付
                    </button>
                  </template>
                </template>
              </td>
              <td>
                <i class="mdi mdi-arrow-right fa-2"></i>
              </td>
            </tr>
          </template>
        </tbody>
      </table>
      <nav id="pagination-box" class="float-end">
        <my-pagination
          name="pagination"
          :row-count="sc.rowCount"
          :page-total="sc.pageTotal"
          :page-no="sc.pageNo"
          @next-page="nextPage"
          @prev-page="prevPage"
          @direct-page="directPage"
        ></my-pagination>
      </nav>
    </template>
  </div>
</template>

<script>
import {
  searchBills,
  getBillTypeDesc,
  auditBill,
  writeOffSingleBill,
  finishBillPayment,
  searchDataTemplates,
} from "@/api/bill.js";
import { APP_FLIGHT_PATH, showCustomerName } from "@/common/common.js";
import MyPagination from "@/components/my-pagination_h5.vue";
import MyDatePicker from "@/components/my-datepicker.vue";
import MySelectCustomer from "@/components/my-select2-customer.vue";
import MySelectSupplier from "@/components/my-select2-supplier.vue";

export default {
  name: "MyBills",
  components: {
    MyDatePicker,
    MyPagination,
    MySelectCustomer,
    MySelectSupplier,
  },
  data() {
    return {
      showSearchForm: false,
      orders: [],
      sc: {
        rowCount: 0,
        pageNo: 1,
        pageSize: 10,
        pageTotal: 0,
      },
      beginDate: "",
      endDate: "",
      etdzDateBegin: "",
      etdzDateEnd: "",
      auditDateBegin: "",
      auditDateEnd: "",
      settleDateBegin: "",
      settleDateEnd: "",
      billType: -1,
      payType: 0,
      customerId: -1,
      supplierId: 0,
      billNum: "",
      orderNo: "",
      flightOrderNo: "",
      remark: "",
      costCenter: "",
      settlementNo: "",
      reviewed: -1,
      bePaid: -1,
      paymentStatus: -1,
      intlTicket: -1,
      downloadFormat: 0,
      orderBy: 3,

      templates: [],

      totalAmount: 0,
      totalCost: 0,
      totalProfit: 0,
    };
  },
  computed: {
    isAdmin() {
      return this.$store.getters.isAdmin;
    },
  },
  activated: function () {
    this.searchBills();
    this.searchDataTemplates();
  },
  methods: {
    showLoading: function (loadingText) {
      this.$store.commit("showLoading", {
        loading: true,
        loadingText: loadingText,
      });
    },
    hideLoading: function () {
      this.$store.commit("showLoading", { loading: false });
    },
    showErrMsg: function (msg, msgType) {
      this.$store.dispatch("showAlertMsg", {
        errMsg: msg,
        errMsgType: msgType,
      });
    },
    searchDataTemplates: function () {
      const params = {
        "sc.pageNo": 1,
        "sc.pageSize": 100,
      };

      searchDataTemplates(params, (jsonResult) => {
        this.templates = jsonResult.dataList;
      });
    },
    showSearchOption: function () {
      this.showSearchForm = true;
    },
    searchBills: function () {
      this.showSearchForm = false;
      const params = {
        "sc.pageNo": this.sc.pageNo,
        "sc.pageSize": this.sc.pageSize,
        "sc.beginDate": this.beginDate,
        "sc.endDate": this.endDate,
        "sc.etdzDateBegin": this.etdzDateBegin,
        "sc.etdzDateEnd": this.etdzDateEnd,
        "sc.auditDateBegin": this.auditDateBegin,
        "sc.auditDateEnd": this.auditDateEnd,
        "sc.settleDateBegin": this.settleDateBegin,
        "sc.settleDateEnd": this.settleDateEnd,
        "sc.billNum": this.billNum,
        "sc.orderNo": this.orderNo,
        "sc.flightOrderNo": this.flightOrderNo,
        "sc.remark": this.remark,
        "sc.costCenter": this.costCenter,
        "sc.settlementNo": this.settlementNo,
        "sc.intlTicket": this.intlTicket,
        "sc.supplierId": this.supplierId,
        "sc.orderBy": this.orderBy,
        reviewed: this.reviewed,
        billType: this.billType,
        customerId: this.customerId,
        payType: this.payType,
        bePaid: this.bePaid,
        paymentStatus: this.paymentStatus,
      };

      this.showLoading("加载中");

      searchBills(
        params,
        (jsonResult) => {
          this.orders = jsonResult.dataList;
          this.sc = jsonResult.page;
          this.calcTotal();
        },
        () => {
          this.hideLoading();
        }
      );
    },
    auditBillDone: function (id) {
      auditBill(id, (v) => {
        if (v.status === "OK") {
          this.showErrMsg("操作成功");
          this.searchBills();
        } else {
          this.showErrMsg("操作失败: " + jsonResult.errmsg);
        }
      });
    },
    writeOffBill: function (id) {
      writeOffSingleBill(id, (v) => {
        if (v.status !== "OK") {
          this.showErrMsg(v.errmsg, "danger");
        } else {
          this.showErrMsg("操作成功");
          this.searchBills();
        }
      });
    },
    finishPayment: function (id) {
      //完成支付
      finishBillPayment(id, (v) => {
        if (v.status !== "OK") {
          this.showErrMsg(v.errmsg, "danger");
        } else {
          this.showErrMsg("操作成功");
          this.searchBills();
        }
      });
    },
    showBillTypeDesc: function (val) {
      return getBillTypeDesc(val);
    },
    calcTotal: function () {
      this.totalAmount = 0;
      this.totalCost = 0;
      this.totalProfit = 0;

      for (const info of this.orders) {
        this.totalAmount += info.billSum;
        this.totalCost += info.cost;
        this.totalProfit += info.profit;
      }

      this.totalAmount = Math.round(this.totalAmount * 100) / 100;
      this.totalCost = Math.round(this.totalCost * 100) / 100;
      this.totalProfit = Math.round(this.totalProfit * 100) / 100;
    },
    reset: function () {
      this.customerId = -1;
      this.sc.pageNo = 1;
      this.beginDate = "";
      this.endDate = "";
      this.etdzDateBegin = "";
      this.etdzDateEnd = "";
      this.auditDateBegin = "";
      this.auditDateEnd = "";
      this.settleDateBegin = "";
      this.settleDateEnd = "";
      this.billType = -1;
      this.billNum = "";
      this.orderNo = "";
      this.flightOrderNo = "";
      this.remark = "";
      this.costCenter = "";
      this.settlementNo = "";
      this.reviewed = -1;
      this.bePaid = -1;
      this.paymentStatus = -1;
      this.intlTicket = -1;
      this.supplierId = 0;
    },
    downloadBillInfo: function () {
      const params =
        "sc.pageNo=" +
        this.sc.pageNo +
        "&sc.beginDate=" +
        this.beginDate +
        "&sc.endDate=" +
        this.endDate +
        "&reviewed=" +
        this.reviewed +
        "&billType=" +
        this.billType +
        "&customerId=" +
        this.customerId +
        "&payType=" +
        this.payType +
        "&bePaid=" +
        this.bePaid +
        "&paymentStatus=" +
        this.paymentStatus +
        "&sc.billNum=" +
        this.billNum +
        "&sc.orderNo=" +
        this.orderNo +
        "&sc.flightOrderNo=" +
        this.flightOrderNo +
        "&sc.remark=" +
        this.remark +
        "&sc.costCenter=" +
        this.costCenter +
        "&sc.settlementNo=" +
        this.settlementNo +
        "&sc.etdzDateBegin=" +
        this.etdzDateBegin +
        "&sc.etdzDateEnd=" +
        this.etdzDateEnd +
        "&sc.auditDateBegin=" +
        this.auditDateBegin +
        "&sc.auditDateEnd=" +
        this.auditDateEnd +
        "&sc.settleDateBegin=" +
        this.settleDateBegin +
        "&sc.settleDateEnd=" +
        this.settleDateEnd +
        "&sc.intlTicket=" +
        this.intlTicket +
        "&sc.supplierId=" +
        this.supplierId +
        "&format=" +
        this.downloadFormat;

      const url = APP_FLIGHT_PATH + "/downloadBillInfo.do?" + params;
      // console.log(url)
      window.open(url);
    },
    prevPage: function () {
      this.sc.pageNo = this.sc.pageNo - 1;
      if (this.sc.pageNo < 1) this.sc.pageNo = 1;
      this.searchBills();
    },
    nextPage: function () {
      this.sc.pageNo = this.sc.pageNo + 1;
      this.searchBills();
    },
    directPage: function (pageNo) {
      this.sc.pageNo = pageNo;
      this.searchBills();
    },
    showCustomerName: function (info) {
      return showCustomerName(info, 0);
    },
    showDetail: function (id) {
      this.$router.push("/h5/bill/detail/" + id);
    },
  },
};
</script>